package com.tdx.tnv.magicads;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.tdx.androidlibs.download.RegularDownload;
import vn.tdx.androidlibs.util.NetworkUltis;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.tdx.tnv.magicads.imageloader.ImageLoader;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MagicAds extends DialogFragment {
	private static final String TAG = "MagicAds";

	private static MagicsAdsAdapter mAdsAdapter;
	private static List<App> mlistApps;
	private static boolean isReady = false;
	private ListView mlistApp;
	private LinearLayout mlayoutMagicAds;

	private static int mAdsType = -1;

	public static final int ADS_SEX = 1;
	public static final int ADS_TV = 2;

	public static final String EXTRA_ADS_TYPE = "EXTRA_ADS_TYPE";

	private static DataLoader mDataLoader;
	private BroadcastReceiver mBroadcastReceiver;
	DownloadManager mDownloadManager;

	public static MagicAds newInstance(int adsType) {
		MagicAds magicAds = new MagicAds();
		Bundle bundle = new Bundle();
		bundle.putInt(EXTRA_ADS_TYPE, adsType);
		magicAds.setArguments(bundle);
		mAdsType = adsType;
		return magicAds;
	}

	public MagicAds() {
		mDataLoader = new DataLoader();
		mDataLoader.execute();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAdsType = getArguments().getInt(EXTRA_ADS_TYPE);
		mDownloadManager = (DownloadManager) getActivity().getSystemService(
				Context.DOWNLOAD_SERVICE);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.magicads, container, false);
		initView(view);
		if (mlistApps != null) {
			mAdsAdapter = new MagicsAdsAdapter(mlistApps, getActivity());
			mlistApp.setAdapter(mAdsAdapter);
		}
		getDialog().setTitle(R.string.new_app);
		setViewTop(this.view);
		return view;
	}

	private void initView(View view) {
		mlayoutMagicAds = (LinearLayout) view
				.findViewById(R.id.layout_magicads);
		mlistApp = (ListView) view.findViewById(R.id.magicads_list);

		mBroadcastReceiver = new BroadcastReceiver() {

			@SuppressLint("InlinedApi")
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

					long downloadId = intent.getLongExtra(
							DownloadManager.EXTRA_DOWNLOAD_ID, 0);
					Query query = new Query();
					query.setFilterById(downloadId);
					Cursor c = mDownloadManager.query(query);

					String uriFile = null;
					if (c.moveToFirst()) {
						uriFile = c
								.getString(c
										.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
						Log.i(TAG, "Uri local=" + uriFile);
					}

					// start install app
					Intent i = new Intent(Intent.ACTION_VIEW);
					i.setDataAndType(Uri.parse(uriFile),
							"application/vnd.android.package-archive");
					i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(i);

					// start notification download success
					NotificationCompat.Builder builder = new NotificationCompat.Builder(
							getActivity());
					builder.setDefaults(Notification.DEFAULT_ALL);

					PendingIntent pendingIntent = PendingIntent.getActivity(
							getActivity(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
					builder.setContentIntent(pendingIntent);

					NotificationManager notificationManager = (NotificationManager) getActivity()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					notificationManager.notify(1, builder.build());

				}
			}
		};

		mlistApp.setOnItemClickListener(new OnItemClickListener() {

			@SuppressLint("NewApi")
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MagicsAdsAdapter magicsAdsAdapter = (MagicsAdsAdapter) arg0
						.getAdapter();
				App app = (App) magicsAdsAdapter.getItem(arg2);
				int adsType = app.getType();
				switch (adsType) {
				case App.Type.APK:
					Request request = new Request(Uri.parse(app.getUrl()));

					File file = getActivity().getExternalFilesDir("apk");
					request.setDestinationUri(Uri.fromFile(file));
					request.setTitle(app.getName());
					request.setMimeType("application/vnd.android.package-archive");

					if (!NetworkUltis.isConnected(getActivity())) {
						showAlertDialog(R.string.notification,
								R.string.require_internet);
						return;
					}
					if (!Environment.MEDIA_MOUNTED.equals(Environment
							.getExternalStorageState())) {
						showAlertDialog(R.string.notification,
								R.string.require_sdcard);
						return;
					}
					showAlertDialog(R.string.notification,
							R.string.process_downloading);
					mDownloadManager.enqueue(request);

					getActivity().registerReceiver(
							mBroadcastReceiver,
							new IntentFilter(
									DownloadManager.ACTION_DOWNLOAD_COMPLETE));
					break;
				case App.Type.DEV:
				case App.Type.SITE:
				case App.Type.PLAY:
					break;

				default:
					break;
				}
			}

		});
	}
	View view;
	public void setViewTop(View view){
		this.view=view;
	}
	public void addViewTop(View view) {
		mlayoutMagicAds.addView(view, 0);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mBroadcastReceiver != null)
			getActivity().unregisterReceiver(mBroadcastReceiver);
	}

	private void showAlertDialog(int title, int message) {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("OK", null);
		builder.show();
	}

	public boolean isReady() {
		return isReady;
	}

	private class DataLoader extends AsyncTask<Void, Void, List<App>> {

		@Override
		protected List<App> doInBackground(Void... params) {
			String url = "https://dl.dropboxusercontent.com/s/na1wludui0iatyp/jsonquangcao.txt?token_hash=AAFQSnIHAERFSplHSdlWPeImkv3_d2-zSzEQYeu-5bYkSQ&dl=1";
			String data = "";
			try {
				data = RegularDownload.downloadFile(url);
				Log.i(TAG, "data=" + data);
				AppList appList = parseJson(data, mAdsType);
				return appList.getAppList();
			} catch (IOException e) {
				e.printStackTrace();
				Log.e(TAG, "IO Exception");
			} catch (JSONException e) {
				e.printStackTrace();
				Log.e(TAG, "Parse JSON error");
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<App> result) {
			super.onPostExecute(result);
			if (result != null) {
				mlistApps = result;
				mAdsAdapter = new MagicsAdsAdapter(result, getActivity());
				isReady = true;
			} else {
				isReady = false;
			}
		}

		private AppList parseJson(String data, int adsType)
				throws JSONException {
			JSONObject jsonObject = new JSONObject(data);
			JSONArray array = null;
			AppList appList = new AppList();
			switch (adsType) {
			case ADS_SEX:
				array = jsonObject.getJSONArray("sex");
				break;
			case ADS_TV:
				array = jsonObject.getJSONArray("tv");
				break;

			default:
				break;
			}
			if (array != null) {
				for (int i = 0; i < array.length(); i++) {
					JSONObject object = array.getJSONObject(i);

					String packageName = object.getString("packageName");
					String name = object.getString("name");
					String des = object.getString("des");
					String url = object.getString("url");
					String icon = object.getString("icon");
					int type = object.getInt("type");
					App app = new App(packageName, name, des, type, url, icon);
					appList.getAppList().add(app);
				}
			}
			return appList;
		}

	}

	private class MagicsAdsAdapter extends BaseAdapter {
		private List<App> mlistApps = new ArrayList<App>();
		private Context mContext;
		private ImageLoader mImageLoader;

		private static final int TOTAL_TYPE = 2;
		private static final int NORMAR = 0;
		private static final int MORE = 1;

		public MagicsAdsAdapter(List<App> list, Context context) {
			mlistApps = list;
			mContext = context;
			mImageLoader = new ImageLoader(context);
		}

		@Override
		public int getCount() {
			return mlistApps.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mlistApps.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public int getViewTypeCount() {
			return TOTAL_TYPE;
		}

		@Override
		public int getItemViewType(int position) {
			if (mlistApps.get(position).getType() == App.Type.DEV) {
				return MORE;
			}
			return NORMAR;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			ViewHolder holder = null;
			if (arg1 == null) {
				holder = new ViewHolder();
				if (getItemViewType(arg0) != MORE) {
					arg1 = View.inflate(mContext,
							R.layout.magicads_item_list_ads, null);
					holder.imageView = (ImageView) arg1
							.findViewById(R.id.magicads_item_list_ads_img);
					holder.txtDescription = (TextView) arg1
							.findViewById(R.id.magicads_item_list_ads_des);

					holder.txtTitle = (TextView) arg1
							.findViewById(R.id.magicads_item_list_ads_title);
					arg1.setTag(holder);
				} else {
					arg1 = View.inflate(mContext,
							R.layout.magicads_item_list_ads_more, null);
				}

			} else {
				if (getItemViewType(arg0) != MORE) {
					holder = (ViewHolder) arg1.getTag();
				}
			}

			if (getItemViewType(arg0) != MORE) {
				holder.txtTitle.setText(mlistApps.get(arg0).getName());
				holder.txtDescription.setText(mlistApps.get(arg0).getDes());
				mImageLoader.DisplayImage(mlistApps.get(arg0).getIcon(),
						holder.imageView);
			}
			return arg1;
		}

		private class ViewHolder {
			public ImageView imageView;
			public TextView txtTitle;
			public TextView txtDescription;
		}
	}
}
